import chalk from 'chalk';
import Koa from 'koa';
import { HttpUtil } from '../utils/http.util';
import { FileUtil } from '../utils/file.util';
import { BaseService } from '../configs/server.config';
import { InitTypeEnum, IProxyOption } from '../models';
import { ProxyFactory, ProxyConfig } from '../factories/proxy-factory';



/**
 * @param {proxy config} options
 * {
 *   target: 'https://172.35.0.2',
 *   context: [] or string; the match of regex
 *   exclude: [] or string; the match of exclude regex
 * }
 * @returns
 */


export default function HttpProxy(options: IProxyOption | IProxyOption[]) {
    const baseLogPath = BaseService.getLogBasePath();
    // init log path
    FileUtil.deepMakeDir(baseLogPath);
    return async (ctx: Koa.Context | any, next: Koa.Next) => {

        const proxyConfig = ProxyConfig.getConfig(options, ctx);
        if (!proxyConfig) {
            await next();
            return;
        }

        const currentProxy = ProxyFactory.getProxy(proxyConfig);

        console.log(chalk.green(currentProxy.initType), '--', ctx.header.referer, '--', ctx.request.url);

        if (currentProxy.initType === InitTypeEnum.local) {
            ctx.response.body = currentProxy.getLocalData(ctx);
            return;
        }
        const requestOptions = currentProxy.getRequestOption(ctx);
        const response: any = await HttpUtil.request(requestOptions);

        if (response.headers['set-cookie']?.length) {
            ctx.response.set('set-cookie', response.headers['set-cookie']);
        }

        if (currentProxy.initType === InitTypeEnum.interface) {
            ctx.response.status = response.statusCode;
        }

        ctx.response.body = currentProxy.getResponse(response, ctx);
    };
};

